import os.path

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

class MouseOperation:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://sahitest.com/demo/clicks.htm')
        self.driver.maximize_window()
        self.ac = ActionChains(self.driver)

    # 退出浏览器
    def quit(self,seconds=3):
        time.sleep(seconds)
        self.driver.quit()

    # 单击
    def click(self):
        # 方式一:
        time.sleep(2)
        input1 = self.driver.find_element(By.XPATH, '//form/input[3]')
        input1.click()
        # 方式二:
        ac = ActionChains(self.driver)
        ac.click(input1).perform()

    # 右击
    def context_click(self):
        time.sleep(2)
        input2 = self.driver.find_element(By.XPATH, '//form/input[4]')
        ac = ActionChains(self.driver)
        ac.context_click(input2).perform()

    # 双击
    def double_click(self):
        time.sleep(2)
        input3 = self.driver.find_element(By.XPATH, '//form/input[2]')
        self.ac.double_click(input3).perform()

    # 拖动
    def drag_and_drop(self):
        self.driver.get('https://sahitest.com/demo/dragDropMooTools.htm')
        time.sleep(2)
        source = self.driver.find_element(By.ID, 'dragger')
        target = self.driver.find_element(By.XPATH, '//div[3]')
        self.ac.drag_and_drop(source,target).perform()

    # 悬停
    def mouseover(self):
        time.sleep(2)
        self.driver.get('https://sahitest.com/demo/mouseover.htm')
        time.sleep(2)
        input = self.driver.find_element(By.XPATH, '//form/input[1]')
        self.ac.move_to_element(input).perform()
        div = self.driver.find_element(By.XPATH, "//div/div")
        self.ac.move_to_element(div).perform()

    # 长按
    def click_and_hold(self):
        time.sleep(2)
        file = os.path.join(os.path.abspath('html'),'mouse_hold.html')
        self.driver.get(file)
        btn = self.driver.find_element(By.ID, 'btn1')
        self.ac.click_and_hold(btn).perform()
        time.sleep(6)


if __name__ == '__main__':
    mo = MouseOperation()
    # mo.click()
    # mo.context_click()
    # mo.double_click()
    # mo.drag_and_drop()
    # mo.mouseover()
    mo.click_and_hold()
    mo.quit()


    # # 打开本地文件
    # # __file__ 指的是当前脚本文件 abspath绝对路径
    # print(os.path.abspath(__file__))
    # print(os.path.abspath('html'))
    # print(os.path.join(os.path.abspath('html'), 'mouse_hold.html'))
    # # dirname 找上一层
    # print(os.path.dirname(os.path.abspath(__file__)))
    # # join 文件路径的拼接
    # print(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'html'))

